using Eno.Application.Dto;
using Eno.Application.Services;
using Eno.Domain.Entity.App;
using Eno.Infrastructure.Tools;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;

namespace Eno.Api.Controllers;


[ApiController]
[Route("api/[controller]")]
public class PermissionController : ControllerBase
{
    private readonly PermissionService _service;

    public PermissionController(PermissionService permissionService)
    {
        _service = permissionService;
    }

    [HttpGet]
    public async Task<IActionResult> GetPermissionAsync()
    {
        var listPermission = await _service.GetAppPermissionsAsync();
        return Ok(Tips<IEnumerable<AppPermission>>.Success(listPermission, "查询权限成功"));
    }

    [HttpGet("{permissionId}")]
    public async Task<IActionResult> GetPermissionDetailAsync(Guid permissionId)
    {
        // 查询权限
        var permission = await _service.GetAppPermissionById(permissionId);
        if (permission == null)
            return Ok(Tips<string>.Fail("未找到权限"));

        // 查询拥有该权限的所有角色
        var roles = await _service.GetRolesByPermissionId(permissionId);

        // 返回权限和角色
        return Ok(Tips<object>.Success(new {
            permission,
            roles
        }, "查询权限详情成功"));
    }

    [HttpPost]
    public async Task<IActionResult> AdditionPermissionAsync([FromBody] PermissionDto permissionDto)
    {
        var number = await _service.AdditionPermissionAsync(permissionDto.PermissionName);
        if (number == 0) return Ok(Tips<string>.Fail(""));
        return Ok(Tips<int>.Success(number, "新增权限操作成功"));
    }

    [HttpPost("{permissionId}")]
    public async Task<IActionResult> UpdatePermissionAsync(Guid permissionId, PermissionDto permissionDto)
    {
        var number = await _service.UpdatePermissionAsync(permissionId, permissionDto);
        if (number == 0) return Ok(Tips<string>.Fail(""));
        return Ok(Tips<int>.Success(number, "修改权限操作成功"));
    }

    [HttpDelete("{permissionId}")]
    public async Task<IActionResult> DeletePermissionAsync(Guid permissionId)
    {
        var number = await _service.DeletePermissionAsync(permissionId);
        if (number == 0) return Ok(Tips<string>.Fail(""));
        return Ok(Tips<int>.Success(number, "删除权限操作成功"));
    }

}